﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Dynamitey.DynamicObjects;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class EC_ReceivingInterfaceBusiness : ECInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption EC_Query;

        //接口信息
        public Base_InterfaceOption EC_Sync;
        public EC_ReceivingInterfaceBusiness()
        {
            this.InterfaceName = "易仓入库单";
            //索引字段
            this.MapFields = GetMapField("EC_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            EC_Query = this.interfaceOption.Where(x => x.OperateType == "EC_Query").First();
            EC_Sync = this.interfaceOption.Where(x => x.OperateType == "EC_Sync").First();
            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求前的事件
            this.BeforeNoQueryEvent += EC_ReceivingInterfaceBusiness_BeforeNoQueryEvent; ;
            //执行非查询请求中的事件
            this.OnNoQueryEvent += EC_ReceivingInterfaceBusiness_OnNoQueryEvent; ;
            //执行非查询请求后的事件
            this.AfterNoQueryEvent += EC_ReceivingInterfaceBusiness_AfterNoQueryEvent;

        }



        /// <summary>
        /// 执行非查询请求前事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void EC_ReceivingInterfaceBusiness_BeforeNoQueryEvent(object sender, EC_NoQueryEventArgs noQueryEventArgs)
        {
            try
            {
                //获取请求的参数
                string pairs_s = noQueryEventArgs.APINodes.Where(x => x.TargetField == "biz_content").First().SreachKey;
                JObject pairs_o = JObject.Parse(pairs_s);
                noQueryEventArgs.CustomData = pairs_o;
                //获取
                noQueryEventArgs.CustomData2 = noQueryEventArgs.APINodes.Where(x => x.TargetField == "app_key").First().SreachKey;

            }
            catch (Exception ex)
            {

            }
        }




        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="EC_NoQueryEventArgs"></param>
        private void EC_ReceivingInterfaceBusiness_OnNoQueryEvent(object sender, EC_NoQueryEventArgs noQueryEventArgs)
        {

            //获取请求的数据
            EC_ReqDTO_SyncReceiving data = new EC_ReqDTO_SyncReceiving();
            data.timestamp = DateTime.Now.ToUnixTimeStampMillis();
            //data.biz_content = noQueryEventArgs.APINodes.Where(x => x.TargetField == "biz_content").First().SreachKey;
            data.biz_content = noQueryEventArgs.Data.ToJson();
            data.sign = "";
            //获取Sign
            noQueryEventArgs.reqData = GetJsonData(noQueryEventArgs.APINodes, noQueryEventArgs.ParentNode, data);
            var reqData = JObject.Parse(noQueryEventArgs.reqData);
            //获取所有json节点的信息
            var nodes = noQueryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == EC_Sync.Id);
            //需要将请求的数据拼接到url中，先转换成字典
            Dictionary<string, object> reqKeyValue = new Dictionary<string, object>();
            foreach (var item in nodes)
            {
                if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                {
                    reqKeyValue.Add(item.TargetField, reqData[item.TargetField].ToString());
                }
            }

            data.sign = GetMD5Sign(reqKeyValue, noQueryEventArgs.CustomData2.ToString());
            noQueryEventArgs.reqData = GetJsonData(noQueryEventArgs.APINodes, noQueryEventArgs.ParentNode, data);


        }
        /// <summary>
        /// 执行非查询请求后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void EC_ReceivingInterfaceBusiness_AfterNoQueryEvent(object sender, EC_NoQueryEventArgs noQueryEventArgs)
        {
            try
            {
                //将返回的结果转换成对象
                var res = JObject.Parse(noQueryEventArgs.Result_s);
                
                //请求的数据，主要为了获取请求的原平台单号
                var temp = (EC_ReqDTO_SyncReceiving.Biz_Content)noQueryEventArgs.Data;
                //API请求是否成功
                if (res["code"].ToString() == "200")//成功将返回的单号更新到数据库表中
                {
                    //获取返回的新单号
                    var resMsg = (EC_ResDTO)JsonConvert.DeserializeObject<EC_ResDTO>(res["biz_content"].ToString());
                    temp.ResultMsg = resMsg.receiving_code;
                    noQueryEventArgs.Success = true;
                    
                }
                else if (res["code"].ToString() == "300" && res.ToString().Contains("系统已存在"))//已同步的单更新已同步标志
                {
                    //已同步的单号不再同步
                    noQueryEventArgs.Success = true;
                    var resMsg= (List<EC_ResDTO>)JsonConvert.DeserializeObject<List<EC_ResDTO>>(res["biz_content"].ToString());
                    temp.ResultMsg = string.Join(",", resMsg.Select(x => x.errorMsg));
                    AddLog(SqlDb, $"同步单号:{temp.reference_no}", InterfaceName, "EC_Sync", res.ToString());
                }
                else if (res["code"].ToString() == "300")//其他记录信息
                {
                    noQueryEventArgs.Success = true;
                    var resMsg = (List<EC_ResDTO>)JsonConvert.DeserializeObject<List<EC_ResDTO>>(res["biz_content"].ToString());
                    temp.ResultMsg = string.Join(",", resMsg.Select(x => x.errorMsg));
                    AddLog(SqlDb, $"同步单号:{temp.reference_no}", InterfaceName, "EC_Sync", res.ToString());
                }
                else//错误信息直接报错处理
                {
                    noQueryEventArgs.Success = false;
                    var resMsg = (List<EC_ResDTO>)JsonConvert.DeserializeObject<List<EC_ResDTO>>(res["biz_content"].ToString());
                    temp.ResultMsg = string.Join(",", resMsg.Select(x => x.errorMsg));
                    AddLog(SqlDb, $"同步单号:{temp.reference_no}", InterfaceName, "EC_Sync", res.ToString());
                }
            }
            catch (Exception ex)
            {
                noQueryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", noQueryEventArgs.Result_s);
                //Thread.Sleep(30000);
            }
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的参数
                string pairs_s = queryEventArgs.APINodes.Where(x => x.TargetField == "biz_content").First().SreachKey;
                JObject pairs_o = JObject.Parse(pairs_s);
                queryEventArgs.CustomData = pairs_o;
                //获取
                queryEventArgs.CustomData2 = queryEventArgs.APINodes.Where(x => x.TargetField == "app_key").First().SreachKey;
                //设置查询第几页
                queryEventArgs.Page.PageIndex = 1;
                //一页的数量
                queryEventArgs.Page.PageSize = pairs_o["page_size"].ToString().ToInt();
                //一页的数量
                queryEventArgs.Page.Total = pairs_o["date_for"].ToString().ToInt();
            }
            catch (Exception ex)
            {

            }


        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的数据
                EC_ReqDTO data = new EC_ReqDTO();
                data.timestamp = DateTime.Now.ToUnixTimeStampMillis();
                var par = (JObject)queryEventArgs.CustomData;
                par["page"] = queryEventArgs.Page.PageIndex;
                par["date_for"] = DateTime.Now.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd");//入库单开始日期,等于
                par["date_to"] = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");//入库单截止日期,不等于
                data.biz_content = par.ToJson();
                data.sign = "";
                //获取Sign
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
                var reqData = JObject.Parse(queryEventArgs.reqData);
                //获取所有json节点的信息
                var nodes = queryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == EC_Query.Id);
                //需要将请求的数据拼接到url中，先转换成字典
                Dictionary<string, object> reqKeyValue = new Dictionary<string, object>();
                foreach (var item in nodes)
                {
                    if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                    {
                        reqKeyValue.Add(item.TargetField, reqData[item.TargetField].ToString());
                    }
                }
                data.sign = GetMD5Sign(reqKeyValue, queryEventArgs.CustomData2.ToString());
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                EC_ReceivingDTO result = (EC_ReceivingDTO)JsonConvert.DeserializeObject<EC_ReceivingDTO>(queryEventArgs.ResultStr);
                if (result.message == "Success")
                {
                    EC_Receiving_Data DTO_data = (EC_Receiving_Data)JsonConvert.DeserializeObject<EC_Receiving_Data>(result.biz_content);
                    //查询数量小于单页最大数量查询完成
                    if (DTO_data.data.Count < queryEventArgs.Page.PageSize)
                    {
                        queryEventArgs.Page.Complete = true;
                    }
                    else
                    {
                        //查询下一页
                        queryEventArgs.Page.PageIndex++;
                    }
                    queryEventArgs.Rows = DTO_data.data;
                    queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
                Thread.Sleep(20000);
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                Thread.Sleep(20000);
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            //List<EC_Receiving> QQ = await this.QueryAsync<EC_Receiving>(this.EC_Query, SqlDb);
            List<EC_ReqDTO_SyncReceiving.Biz_Content> biz_s=new List<EC_ReqDTO_SyncReceiving.Biz_Content>();

            EC_ReqDTO_SyncReceiving.Biz_Content biz_Content=new EC_ReqDTO_SyncReceiving.Biz_Content();

            biz_Content.action_type = "ADD";
            biz_Content.receiving_status = 5;
            biz_Content.receiving_type = 1;
            biz_Content.warehouse_id = 1;
            biz_Content.warehouse_code = "";
            biz_Content.reference_no = "同步测试01";
            biz_Content.tracking_number = "001,002";
            biz_Content.expected_date = "2025-10-29";
            biz_Content.description = "同步测试";

            EC_ReqDTO_SyncReceiving.Biz_Content.Product_List product = new EC_ReqDTO_SyncReceiving.Biz_Content.Product_List();
            product.product_sku = "TEST001";
            product.product_qty = 1;
            product.shipping_method = "";
            product.is_qc = 1;
            biz_Content.product_list.Add(product);
            biz_s.Add(biz_Content);
            await this.ExecuteNoQuery<EC_ReqDTO_SyncReceiving.Biz_Content>(biz_s, this.EC_Sync, SqlDb);
        }

        /// <summary>
        /// 获取MD5 sign
        /// </summary>
        /// <param name="url"></param>
        /// <param name="access_token"></param>
        /// <param name="app_key"></param>
        /// <param name="reqData"></param>
        /// <returns></returns>
        public string GetMD5Sign(Dictionary<string, object> reqKeyValue,string secret_Key)
        {

            reqKeyValue = reqKeyValue.OrderBy(x => x.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            StringBuilder sb = new StringBuilder();
            foreach (var item in reqKeyValue)
            {
                sb.Append(item.Key);
                sb.Append("=");
                sb.Append(item.Value);
                sb.Append("&");
            }
            //移除左后一个&连接符号
            sb.Remove(sb.Length - 1, 1);
            sb.Append(secret_Key);
            string sign = sb.ToString().Replace("\n", "").Replace("\r", "").Replace(" ", "");
            //MD5加密
            sign = sign.ToMD5String().ToLower();
            return sign;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
